package com.atguigu.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore( 3 );//模拟三个车位 限流
         //6个小车争3个停车位，先到先得
        for (int i = 1;i<=6;i++){
            int finalI = i;
            new Thread( ()->{
                boolean flag = false;
                try {
                    semaphore.acquire();
                    flag = true;
                    System.out.println(Thread.currentThread().getName()+"\t"+"占位成功，"+finalI);

                    //暂停几秒钟线程
                    try{
                        TimeUnit.SECONDS.sleep( 3 );
                    }catch (InterruptedException e){e.printStackTrace();}
                    System.out.println(Thread.currentThread().getName()+"\t"+"离开");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    if(flag){
                        semaphore.release();
                    }
                }
            } ,String.valueOf(  i)).start();
        }
    }
}
